<template>
    <div class="params_wrap">
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 内容主体区域 -->
        <el-card>
            <!-- 提示 -->
            <el-alert class="el-icon-warning" title="注意：只允许为第三级分类设置相关参数" type="success" :closable="false"></el-alert>
            <!-- 商品分类选择 -->
            <div class="goods_select">
                <span>选择商品分类：</span>
                <el-cascader :key="cascaderBug" v-model="currentClassKeys" :options="goodsClassList" :props="goodsProps" @change="handleChange"></el-cascader>
            </div>
            <!-- 动态and静态参数选择器 -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <!-- 动态参数区域 -->
                <el-tab-pane label="动态参数" name="many">
                    <!-- 添加参数按钮 -->
                    <el-button @click="showAddParams" :disabled="isDisabled" type="primary">添加动态参数</el-button>
                    <!-- 参数列表 -->
                    <el-table :data="manyParamsList" border style="width: 100%">
                        <el-table-column type="index"></el-table-column>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag @close="removeParams(scope.row,index)" :key="index" v-for="(item, index) in scope.row.attr_vals" closable>{{item}}</el-tag>
                                <!-- 动态编辑参数 -->
                                <el-input class="input-new-tag newParams" v-if="scope.row.inputVisible" v-model.trim="scope.row.inputValue" ref="saveTagInput"
                                size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column prop="attr_name" label="操作">
                            <template slot-scope="scope">
                                <el-button @click="showModifyForm(scope.row)" type="primary" icon="el-icon-edit">编辑</el-button>
                                <el-button @click="removeParamsAll(scope.row)" type="primary" icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                </el-tab-pane>


                <!-- 静态参数区域 -->
                <el-tab-pane label="静态参数" name="only">
                    <!-- 添加参数按钮 -->
                    <el-button @click="showAddParams" :disabled="isDisabled" type="primary">添加静态参数</el-button>
                    <!-- 参数列表 -->
                    <el-table :data="onlyParamsList" border style="width: 100%">
                        <el-table-column type="index"></el-table-column>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag @close="removeParams(scope.row,index)" :key="index" v-for="(item, index) in scope.row.attr_vals" closable>{{item}}</el-tag>
                                <!-- 静态编辑参数 -->
                                <el-input class="input-new-tag newParams" v-if="scope.row.inputVisible" v-model.trim="scope.row.inputValue" ref="saveTagInput"
                                size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column prop="attr_name" label="操作">
                            <template slot-scope="scope">
                                <el-button @click="showModifyForm(scope.row)" type="primary" icon="el-icon-edit">编辑</el-button>
                                <el-button @click="removeParamsAll(scope.row)" type="primary" icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                </el-tab-pane>
                
            </el-tabs>
        </el-card>

        <!-- 添加对话框 -->
        <el-dialog title="提示" :visible.sync="isShowAddParams" width="50%">
            <!-- 表单区域 -->
            <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="100px">
                <el-form-item :label="activeName == 'many' ? '动态参数' : '静态参数'" prop="attr_name">
                    <el-input v-model="addParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowAddParams = false">取 消</el-button>
                <el-button type="primary" @click="submitAddParamsForm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑对话框 -->
        <el-dialog title="修改参数名称" :visible.sync="isShowModifyParams" width="50%">
            <!-- 表单区域 -->
            <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="ModifyParamsFormRef" label-width="100px">
                <el-form-item :label="activeName == 'many' ? '动态参数' : '静态参数'" prop="attr_name">
                    <el-input v-model="addParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowModifyParams = false">取 消</el-button>
                <el-button type="primary" @click="submitModifyParamsForm">确 定</el-button>
            </span>
        </el-dialog>


    </div>
</template>

<script>
export default {
    data() {
        return {
            // 当前所选择的分类值
            currentClassKeys: '',
            // 商品分类列表
            goodsClassList: [],
            // 级联选择器配置
            goodsProps: {
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name'
            },
            // 解决级联选择器的BUG
            cascaderBug: 0,
            // 获取用户点击的是动态参数还是静态参数
            activeName: 'many',
            // 存储动态参数列表
            manyParamsList: [],
            onlyParamsList: [],
            // 控制输入框显示与隐藏
            inputVisible: false,
            // 输入框的值
            inputValue: '',
            // 显示或隐藏添加参数的对话框
            isShowAddParams: false,
            // 添加参数的表单参数
            addParamsForm: {
                attr_name: ''
            }, 
            // 添加参数的验证规则
            addParamsFormRules: {
                attr_name: [
                    { required: true, message: '请输入参数名称', trigger: 'blur' },
                ]
            },
            // 获取添加参数的ID
            addParamsID: 0,
            // 显示编辑对话框
            isShowModifyParams: false,
            // 获取被修改的参数ID
            modifyID: 0,
        }
    },
    created() {
        this.getGoodsClassList();
    },
    computed: {
        // 如果选中了三级分类就启用添加参数按钮，否则就禁用
        isDisabled() {
            if (this.currentClassKeys.length != 3) return true;
            return false;
        }
    },
    methods: {
        // 获取商品分类列表
        async getGoodsClassList() {
            const { data: res } = await this.$http.get('categories');
            if (res.meta.status != 200) return this.$message.error('获取商品分类失败');
            this.goodsClassList = res.data;
            ++this.cascaderBug;
        },
        // 分类被选择时触发
        async handleChange() {
            // 不是三级分类清空数组
            if (this.currentClassKeys.length != 3) {
                this.currentClassKeys = [];
                this.manyParamsList = [];
                this.onlyParamsList = [];
                return
            }
            this.getParamsList();
        },
        // 动态参数或静态参数被点击时触发
        handleClick() {
            this.getParamsList();
        },
        // 获取参数列表
        async getParamsList() {
            this.addParamsID = this.currentClassKeys[2];
            if (this.addParamsID) {
                const { data: res } = await this.$http.get(`categories/${this.currentClassKeys[2]}/attributes`, {
                    params: { sel: this.activeName}
                });

                // 把参数转换成数组
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
                    item.inputVisible = false;
                    item.inputValue = '';
                });

                // 判断是动态参数还是静态参数的数据
                if (this.activeName === 'many') {
                    this.manyParamsList = res.data;
                } else {
                    this.onlyParamsList = res.data;
                }
            }
        },
        // 删除参数
        async removeParams(params, index) {
            params.attr_vals.splice(index, 1);
            const { data: res } = await this.$http.put(`categories/${params.cat_id}/attributes/${params.attr_id}`, {
                attr_name: params.attr_name,
                attr_sel: params.attr_sel,
                attr_vals: params.attr_vals.join(' ')
            });
        },
        // 输入框回车键和失去焦点会触发的函数
        async handleInputConfirm(params) {
            params.inputVisible = false;
            // 判断文本是否为空，不为空就发起请求
            if (params.inputValue.length != 0) {
                params.attr_vals.push(params.inputValue);
                const { data: res } = await this.$http.put(`categories/${params.cat_id}/attributes/${params.attr_id}`, {
                    attr_name: params.attr_name,
                    attr_sel: params.attr_sel,
                    attr_vals: params.attr_vals.join(' ')
              });
              if (res.meta.status != 200) return this.$message.error('添加参数失败');
              this.$message.success('添加参数成功');
            }
        },
        // 显示输入框
        showInput(row) {
            row.inputVisible = true;
            // 自动获得输入焦点
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        // 显示添加参数的对话框
        showAddParams() {
            this.addParamsForm.attr_name = '';
            this.isShowAddParams = true;
        },
        // 提交添加参数表单
        submitAddParamsForm() {
            this.$refs.addParamsFormRef.validate(async valid => {
                if (!valid) return this.$message.error('请输入参数名');
                const { data: res } = await this.$http.post(`categories/${this.addParamsID}/attributes`, {
                    attr_name: this.addParamsForm.attr_name,
                    attr_sel: this.activeName,
                });
                this.isShowAddParams = false;
                this.getParamsList();
            });
            

        },
        // 显示编辑对话框
        showModifyForm(id) {
            this.isShowModifyParams = true;
            this.modifyID = id;
            this.addParamsForm.attr_name = id.attr_name;
        },
        // 提交编辑表单
        submitModifyParamsForm() {
            this.$refs.ModifyParamsFormRef.validate(async valid => {
                if (!valid) return this.$message.error('修改失败');
                const { data: res } = await this.$http.put(`categories/${this.modifyID.cat_id}/attributes/${this.modifyID.attr_id}`, {
                    attr_name: this.addParamsForm.attr_name,
                    attr_sel: this.activeName,
                });
                if (res.meta.status != 200) return this.$message.error('修改参数名失败');
                this.$message.success('修改成功');
                this.isShowModifyParams = false;
                this.getParamsList();
            });
        },
        // 删除参数
        removeParamsAll(id) {
            this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`categories/${id.cat_id}/attributes/${id.attr_id}`);
                if (res.meta.status != 200) return this.$message.error('删除失败');
                this.$message.success('删除成功');
                this.getParamsList();
            }).catch(() => {
                console.log(1);
                this.$message.info('取消了删除操作');
            });
        }
    }
}
</script>

<style lang="less" scoped>
.el-tabs {
    margin-top: 50px;
}
.el-tag {
    margin: 0 10px;
}
.newParams {
    width: 20%;
}
</style>